{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import print_function\n",
    "import argparse\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "import torch.optim as optim\n",
    "from torchvision import datasets, transforms\n",
    "from torch.optim.lr_scheduler import StepLR"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Argument():\n",
    "    def __init__(self, batch_size=64, test_batch_size=1000, epochs=14, lr=1.0,\n",
    "                gamma=0.7,no_cuda=False, save_model=False):\n",
    "        \n",
    "        self.batch_size = batch_size\n",
    "        self.test_batch_size = test_batch_size\n",
    "        self.epochs = epochs\n",
    "        self.lr = lr\n",
    "        self.gamma = gamma\n",
    "        self.no_cuda = no_cuda\n",
    "        self.save_model = save_model\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "\n",
    "class Net(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(Net, self).__init__()\n",
    "        self.conv1 = nn.Conv2d(1, 32, 3, 1)\n",
    "        self.conv2 = nn.Conv2d(32, 64, 3, 1)\n",
    "        self.dropout1 = nn.Dropout2d(0.25)\n",
    "        self.dropout2 = nn.Dropout2d(0.5)\n",
    "        self.fc1 = nn.Linear(9216, 128)\n",
    "        self.fc2 = nn.Linear(128, 10)\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = self.conv1(x)\n",
    "        x = F.relu(x)\n",
    "        x = self.conv2(x)\n",
    "        x = F.max_pool2d(x, 2)\n",
    "        x = self.dropout1(x)\n",
    "        x = torch.flatten(x, 1)\n",
    "        x = self.fc1(x)\n",
    "        x = F.relu(x)\n",
    "        x = self.dropout2(x)\n",
    "        x = self.fc2(x)\n",
    "        output = F.log_softmax(x, dim=1)\n",
    "        return output\n",
    "\n",
    "\n",
    "def train(args, model, device, train_loader, optimizer):\n",
    "    model.train()\n",
    "    for batch_idx, (data, target) in enumerate(train_loader):\n",
    "        data, target = data.to(device), target.to(device)\n",
    "        optimizer.zero_grad()\n",
    "        output = model(data)\n",
    "        loss = F.nll_loss(output, target)\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "\n",
    "\n",
    "def test(args, model, device, test_loader, epoch):\n",
    "    model.eval()\n",
    "    test_loss = 0\n",
    "    correct = 0\n",
    "    with torch.no_grad():\n",
    "        for data, target in test_loader:\n",
    "            data, target = data.to(device), target.to(device)\n",
    "            output = model(data)\n",
    "            test_loss += F.nll_loss(output, target, reduction='sum').item()  # sum up batch loss\n",
    "            pred = output.argmax(dim=1, keepdim=True)  # get the index of the max log-probability\n",
    "            correct += pred.eq(target.view_as(pred)).sum().item()\n",
    "\n",
    "    test_loss /= len(test_loader.dataset)\n",
    "\n",
    "    print('\\n Epoch {} Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n",
    "        epoch, test_loss, correct, len(test_loader.dataset),\n",
    "        100. * correct / len(test_loader.dataset)))\n",
    "    return 100.*correct / len(test_loader.dataset)\n",
    "\n",
    "\n",
    "def main():\n",
    "    args = Argument()\n",
    "    use_cuda = not args.no_cuda and torch.cuda.is_available()\n",
    "\n",
    "    device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n",
    "\n",
    "    kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}\n",
    "    train_loader = torch.utils.data.DataLoader(\n",
    "        datasets.MNIST('../data', train=True, download=True,\n",
    "                       transform=transforms.Compose([\n",
    "                           transforms.ToTensor(),\n",
    "                           transforms.Normalize((0.1307,), (0.3081,))\n",
    "                       ])),\n",
    "        batch_size=args.batch_size, shuffle=True, **kwargs)\n",
    "    test_loader = torch.utils.data.DataLoader(\n",
    "        datasets.MNIST('../data', train=False, transform=transforms.Compose([\n",
    "                           transforms.ToTensor(),\n",
    "                           transforms.Normalize((0.1307,), (0.3081,))\n",
    "                       ])),\n",
    "        batch_size=args.test_batch_size, shuffle=True, **kwargs)\n",
    "\n",
    "    model = Net().to(device)\n",
    "    optimizer = optim.Adadelta(model.parameters(), lr=args.lr)\n",
    "\n",
    "    scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)\n",
    "    for epoch in range(1, args.epochs + 1):\n",
    "        train(args, model, device, train_loader, optimizer)\n",
    "        test_acc = test(args, model, device, test_loader, epoch)\n",
    "        if test_acc >= 99:\n",
    "            return\n",
    "        scheduler.step()\n",
    "\n",
    "    if args.save_model:\n",
    "        torch.save(model.state_dict(), \"mnist_cnn.pt\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      " Epoch 1 Test set: Average loss: 0.0592, Accuracy: 9829/10000 (98%)\n",
      "\n",
      "\n",
      " Epoch 2 Test set: Average loss: 0.0451, Accuracy: 9871/10000 (99%)\n",
      "\n",
      "\n",
      " Epoch 3 Test set: Average loss: 0.0349, Accuracy: 9884/10000 (99%)\n",
      "\n",
      "\n",
      " Epoch 4 Test set: Average loss: 0.0337, Accuracy: 9890/10000 (99%)\n",
      "\n",
      "\n",
      " Epoch 5 Test set: Average loss: 0.0324, Accuracy: 9907/10000 (99%)\n",
      "\n",
      "\n",
      " Epoch 1 Test set: Average loss: 0.0633, Accuracy: 9800/10000 (98%)\n",
      "\n",
      "\n",
      " Epoch 2 Test set: Average loss: 0.0363, Accuracy: 9876/10000 (99%)\n",
      "\n",
      "\n",
      " Epoch 3 Test set: Average loss: 0.0313, Accuracy: 9896/10000 (99%)\n",
      "\n",
      "\n",
      " Epoch 4 Test set: Average loss: 0.0286, Accuracy: 9911/10000 (99%)\n",
      "\n",
      "\n",
      " Epoch 1 Test set: Average loss: 0.0769, Accuracy: 9775/10000 (98%)\n",
      "\n",
      "\n",
      " Epoch 2 Test set: Average loss: 0.0403, Accuracy: 9873/10000 (99%)\n",
      "\n",
      "\n",
      " Epoch 3 Test set: Average loss: 0.0312, Accuracy: 9896/10000 (99%)\n",
      "\n",
      "\n",
      " Epoch 4 Test set: Average loss: 0.0339, Accuracy: 9884/10000 (99%)\n",
      "\n",
      "\n",
      " Epoch 5 Test set: Average loss: 0.0290, Accuracy: 9903/10000 (99%)\n",
      "\n",
      "57.4 s ± 6.85 s per loop (mean ± std. dev. of 3 runs, 1 loop each)\n"
     ]
    }
   ],
   "source": [
    "%%timeit -n 1 -r 3\n",
    "main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "#timeit gives 45s for 3 epochs on n=1, r=3"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
